import * as React from 'react';
import { get } from 'lodash';
import { Input, InputNumber, Form, Button } from 'antd';

const FormItem = Form.Item;

interface EditFormProps {
  onSubmit: (data: Record<string, any>) => any;
  loading: boolean;
  level: any;
  form: any;
}

class EditForm extends React.Component<EditFormProps> {
  handleSubmit = (e: any) => {
    e.preventDefault();

    const { form, onSubmit } = this.props;
    form.validateFields((err: any, values: any) => {
      if (err) return;
      onSubmit(values);
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { level, loading } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem {...formItemLayout} label="学生等级">
          {getFieldDecorator('level', {
            rules: [
              {
                required: true,
                message: '学生等级是必填项',
              },
            ],
            initialValue: get(level, 'level', null),
          })(
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="学生等级"
              disabled={Boolean(level)}
            />
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="升级阅读量">
          {getFieldDecorator('wordCount', {
            rules: [
              {
                required: true,
                message: '阅读量是必选项',
              },
            ],
            initialValue: get(level, 'wordCount', null),
          })(<InputNumber min={1} style={{ width: '100%' }} placeholder="升级所需阅读量" />)}
        </FormItem>
        <FormItem {...formItemLayout} label="评测通过比例">
          {getFieldDecorator('rate', {
            rules: [
              {
                required: true,
                message: '评测通过比例描述是必选项',
              },
            ],
            initialValue: get(level, 'rate', null),
          })(
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              max={100}
              placeholder="评测通过比例(0 ~ 100)"
            />
          )}
        </FormItem>

        <FormItem {...tailFormItemLayout}>
          <Button icon="save" loading={loading} type="primary" htmlType="submit" size="large">
            提交
          </Button>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create()(EditForm);
